﻿using System;
using System.Drawing;
using System.Windows.Forms;
using YougeBookmark.Services;
using YougeBookmark.Utilities;
using Microsoft.Extensions.DependencyInjection;

namespace YougeBookmark.UI
{
    public partial class MainForm : Form
    {
        private readonly BookmarkManager _bookmarkManager;
        private readonly ClipboardMonitor _clipboardMonitor;
        private readonly Logger _logger;

        // 系统托盘组件
        private NotifyIcon _trayIcon;
        private ContextMenuStrip _trayMenu;

        public MainForm(
            BookmarkManager bookmarkManager,
            ClipboardMonitor clipboardMonitor,
            Logger logger)
        {
            _bookmarkManager = bookmarkManager;
            _clipboardMonitor = clipboardMonitor;
            _logger = logger;

            InitializeComponent();
            InitializeTrayIcon();
            RegisterEvents();
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            SuspendLayout();
            // 
            // MainForm
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(350, 262);
            ControlBox = false;
            Icon = (Icon)resources.GetObject("$this.Icon");
            Margin = new Padding(4, 4, 4, 4);
            MaximizeBox = false;
            MinimizeBox = false;
            Name = "MainForm";
            Opacity = 0D;
            ShowIcon = false;
            ShowInTaskbar = false;
            WindowState = FormWindowState.Minimized;
            this.TopMost = true;
            ResumeLayout(false);
        }

        private void InitializeTrayIcon()
        {
            // 创建托盘菜单
            _trayMenu = new ContextMenuStrip();
            _trayMenu.Items.Add("打开查询", null, OnOpenQuery);
            _trayMenu.Items.Add("管理标签", null, OnManageTags);
            _trayMenu.Items.Add(new ToolStripSeparator());
            _trayMenu.Items.Add("退出", null, OnExit);

            // 创建托盘图标
            _trayIcon = new NotifyIcon
            {
                Text = "优哥书签管理",
                Icon = new Icon(Resources.Resources.appIcon.BytesToStream()),//new Icon(GetType(), "Resources.app.ico"),
                ContextMenuStrip = _trayMenu,
                Visible = true
            };

            // 双击图标打开查询
            _trayIcon.DoubleClick += (s, e) => ShowQueryForm();
        }

        private void RegisterEvents()
        {
            // 注册剪贴板检测事件
            _clipboardMonitor.UrlDetected += async url =>
            {
                try
                {
                    var parsedData = await _bookmarkManager.ParseUrlAsync(url);
                    ShowBookmarkForm(parsedData);
                }
                catch (Exception ex)
                {
                    _logger.Error($"书签创建失败: {ex.Message}", ex);
                    ShowBalloonTip("错误", "解析网页内容失败", ToolTipIcon.Error);
                }
            };
        }

        private void ShowBookmarkForm(ParsedHtmlData data)
        {
            // 使用依赖注入获取窗体实例
            var form = Program.ServiceProvider.GetRequiredService<BookmarkForm>();
            form.InitializeData(data);

            // 确保在主线程显示
            if (form.InvokeRequired)
            {
                BeginInvoke(new Action(() =>
                {
                    form.ShowDialog();
                    //form.BringToFront();
                    //form.Activate();
                }
                ));
            }
            else
            {
                form.ShowDialog();
                //form.BringToFront();
                //form.Activate();
            }
        }

        private void ShowQueryForm()
        {
            var form = Program.ServiceProvider.GetRequiredService<QueryForm>();
            form.Show();
            form.Activate();
        }

        private void ShowTagManagementForm()
        {
            var form = Program.ServiceProvider.GetRequiredService<TagForm>();
            form.ShowDialog();
        }

        private void ShowBalloonTip(string title, string message, ToolTipIcon icon)
        {
            _trayIcon.ShowBalloonTip(3000, title, message, icon);
        }

        #region 事件处理
        private void OnOpenQuery(object sender, EventArgs e) => ShowQueryForm();

        private void OnManageTags(object sender, EventArgs e) => ShowTagManagementForm();

        private void OnExit(object sender, EventArgs e)
        {
            _trayIcon.Visible = false;
            Application.Exit();
        }
        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _trayIcon?.Dispose();
                _trayMenu?.Dispose();
                _clipboardMonitor?.Dispose();
            }
            base.Dispose(disposing);
        }

        // 隐藏主窗体
        protected override void OnLoad(EventArgs e)
        {
            Visible = false;
            ShowInTaskbar = false;
            base.OnLoad(e);
        }
    }
}